if (typeof BIMVIZ !== 'undefined') {
  BIMVIZ.UI.DefaultMarkHarmControl = function (name, iconClass) {
    BIMVIZ.UI.DefaultControl.call(this, name, iconClass)
  }

  BIMVIZ.UI.DefaultMarkHarmControl.prototype = Object.create(BIMVIZ.UI.DefaultControl.prototype)
  BIMVIZ.UI.DefaultMarkHarmControl.constructor = BIMVIZ.UI.DefaultMarkHarmControl

  BIMVIZ.UI.DefaultMarkHarmControl.prototype.onProjectLoaded = function (project) {
    var scope = this
    var bimScene = project.bimScene
    var uitree = null
    var html = '<div id="bv_visibilityBar" class="padding-20 border-bottom-1">\
                <div class="pull-left">\
                    <a class="btn" id="btn_SavePoint"><i class="fa fa-save"></i> 保存</a>\
                </div>\
            </div>\
            <div class="padding-20">\
               <table class="layui-hide" id="TbHarmData"></table>\
            </div>'

    this.parentDiv.html(html)

    this.parentDiv.addClass('nopadding-left nopadding-right').removeClass('padding-20')
    var CanvasWidth = $("canvas[tabindex='-1']").width()
    var CanvasHeight = $("canvas[tabindex='-1']").height()

    // $("#bv_DefaultToolBar_Panel").css("width", CanvasWidth + "px");
    $('#bv_DefaultToolBar_Panel').css('height', '400px')
    // $("#bv_DefaultToolBar_Panel_1").css("width", CanvasWidth + "px")
    $('#bv_DefaultToolBar_Panel_1').css('height', '400px')
    $('#bv_DefaultToolBar_Panel_1').css('position', 'absolute')
    $('#bv_DefaultToolBar_Panel_1').css('top', (CanvasHeight - 400) + 'px')

    var treecontainer = $('#bv_DefaultVisibilityTree')
    var inAntiCheckMode = false
    var _DEFAULTPATH = _ParamsData.ApiServerPath

    var IsChecked = false
    // $('#TbHarmData').bootstrapTable({
    //    url: _DEFAULTPATH + 'bimviz/getdisease/785',       //请求后台的URL（*）
    //    method: 'get',                      //请求方式（*）
    //    // toolbar: '#toolbar',                //工具按钮用哪个容器
    //    striped: true,                      //是否显示行间隔色
    //    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
    //    pagination: true,                   //是否显示分页（*）
    //    sortable: false,                     //是否启用排序
    //    sortOrder: "asc",                   //排序方式
    //    // queryParams: oTableInit.queryParams,//传递参数（*）
    //    sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
    //    pageNumber: 1,                       //初始化加载第一页，默认第一页
    //    pageSize: 10,                       //每页的记录行数（*）
    //    pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
    //    //  search: true,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
    //    //  strictSearch: true,
    //    // showColumns: true,                  //是否显示所有的列
    //    // showRefresh: true,                  //是否显示刷新按钮
    //    //minimumCountColumns: 2,             //最少允许的列数
    //    clickToSelect: true,                //是否启用点击选中行
    //    singleSelect: true, // 单选checkbox
    //    //height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
    //    uniqueId: "KeyId",                     //每一行的唯一标识，一般为主键列
    //    // showToggle: true,                    //是否显示详细视图和列表视图的切换按钮
    //    //cardView: false,                    //是否显示详细视图
    //    //detailView: false,                   //是否显示父子表
    //    columns: [
    //        {
    //            checkbox: true
    //        },
    //    {
    //        field: 'KeyId',
    //        title: 'ID',
    //        cellStyle: {

    //            css: {
    //                'color': 'red'
    //            }
    //        }
    //    },
    //    {
    //        field: 'TrueName',
    //        title: '人员',
    //        width: '30',
    //        cellStyle: {

    //            css: {
    //                'color': 'red'
    //            }
    //        }
    //    },
    //    {
    //        field: 'RecordTime',
    //        title: '时间',
    //        width: '30',
    //        cellStyle: {

    //            css: {
    //                'color': 'red'
    //            }
    //        },
    //        formatter: function (value, row, index) {
    //            return value.substring(0,10);
    //        }

    //    },
    //    {
    //        field: 'ItemDescription',
    //        title: '结构描述',
    //        cellStyle: {
    //            css: {
    //                'color': 'red'
    //            }
    //        }
    //    },
    //        {
    //            field: 'RecordDescription',
    //            title: '记录描述',
    //            cellStyle: {
    //                css: {
    //                    'color': 'red'
    //                }
    //            }
    //        }
    //    ],
    //    onClickRow: function (row, tr, flied) {
    //        //ClearHtmlMarker();
    //        if (!row[0]) {
    //            IsChecked = true;

    //            layer.msg("开始标注");
    //            $("#PointX").val(row.X)
    //            $("#PointY").val(row.Y)
    //            $("#PointZ").val(row.Z)
    //            $("#ComponentCode").val(row.ComponentCode)
    //            $("#TargetXYZ").val(row.CameraXYZ)
    //            $("#KeyId").val(row.KeyId);
    //            if (row.ComponentCode != null && row.X != null) {
    //                    var markerMgr = bimEngine.getMarkerManager();
    //                    var id = new Date().getTime() + 1000;
    //                    var domId = "marker" + id;
    //                    var html = '<div id="' + domId + '" style="position: absolute;">' +
    //                        '<img src="../sdk/bimviz/viz/data/images/markers/business.png" width="30" height="40">' +
    //                        '</div>';
    //                    var point = new THREE.Vector3(row.X, row.Y, row.Z);
    //                    var marker = new BIMVIZ.HtmlMarker(id, domId, domId, point, html, BIMVIZ.Align2D.BottomCenter, 0, "htmlmarker", "marker-text");
    //                    markerMgr.addHtmlMarker(marker);

    //                    bimEngine.acquireSpacePoint(function (data) {

    //                    });
    //                    var target = new THREE.Vector3(row.CameraXYZ.split(',')[0], row.CameraXYZ.split(',')[1], row.CameraXYZ.split(',')[2]);
    //                    var point1 = new THREE.Vector3(row.X, row.Y, row.Z);
    //                    bimEngine.flyFromTo(target, point1)
    //        }

    //        } else {
    //            IsChecked = false;
    //            $("#PointX").val("")
    //            $("#PointY").val("")
    //            $("#PointZ").val("")
    //            $("#ComponentCode").val("")
    //            $("#TargetXYZ").val("")
    //            $("#KeyId").val("")
    //        }

    //        console.log(row)
    //    }
    // });
    // var actionURL = "http://58.49.165.41:86";
    var actionURL = 'http://localhost:8009'
    var PicURL = 'http://58.49.165.41:88/'
    var grid = {
      bind: function () {
        $('#TbHarmData').bootstrapTable({
          columns: [
            {
              title: 'ID',
              align: 'center',
              checkbox: true
            },
            {
              field: 'BridgeName',
              title: '桥名',
              width: 150,
              cellStyle: {
                css: {
                  color: 'red'
                }
              },
              align: 'center'

            }, {
              field: 'TrueName',
              title: '人员',
              align: 'center',
              cellStyle: {
                css: {
                  color: 'red'
                }
              },
              sortable: true
            }, {
              field: 'RecordTime',
              title: '巡检日期',
              cellStyle: {
                css: {
                  color: 'red'
                }
              },
              align: 'center',
              formatter: function (value, row, index) {
                if (value) {
                  return value.toString().substring(0, 10)
                }
              },
              sortable: true
            }, {
              field: 'ItemDescription',
              title: '巡检项',
              cellStyle: {
                css: {
                  color: 'red'
                }
              },
              width: 150,
              sortable: true,
              formatter: function (value, row, index) {
                var whole = value
                if (value != null && value != '') {
                  // value = value.substring(0, 10) + "...";
                  value = value.split('-')[2] + '-' + value.split('-')[3]

                  res = value
                  return '<span title=' + whole + '>' + res + '</span>'
                }
              }
            }, {
              field: 'ItemName',
              title: '病害',
              cellStyle: {
                css: {
                  color: 'blue'
                }
              },
              align: 'center',
              formatter: function (value, row, index) {
                // return "<a style='color:blue;text-decoration:underline  ' class=\"J_menuItem\" href=\"#\" onclick=\"ShowBh(" + row.KeyId + ",'" + value + "')\">" + value + "</a>";
                return '<a style="color:blue;text-decoration:underline  " class="J_menuIte" href="#" onclick="ShowBh(\'' + row.KeyId + '\',\'' + value + '\')">' + value + '</a>'
              },
              sortable: true
            }, {
              field: 'MissionLevel',
              title: '病害等级',
              cellStyle: {
                css: {
                  color: 'red'
                }
              },
              align: 'center',
              formatter: function (value, row, index) {
                if (value == '0' || value == 0) {
                  return ''
                } else if (value == '1' || value == 1) {
                  return '一般'
                } else if (value == '2' || value == 2) {
                  return '严重'
                } else if (value == '3' || value == 3) {
                  return '紧急'
                }
                // else if{
                //    return value;
                // }
              }
            },
            {
              field: 'RecordDescription',
              title: '描述',
              cellStyle: {
                css: {
                  color: 'red'
                }
              },
              width: 350,
              align: 'center',

              formatter: function (value, row, index) {
                var whole = value
                if (value != null && value != '') {
                  if (value.length > 20) {
                    value = value.substring(0, 20) + '...'
                  }
                  res = value
                  return '<span title=' + whole + '>' + whole + '</span>'
                }
              }
            },
            {
              field: 'TimeLimit',
              title: '养护时限',
              cellStyle: {
                css: {
                  color: 'red'
                }
              },
              align: 'center',
              sortable: true,
              formatter: function (value, rows, index) {
                if (value == null || value == 'null' || value == '' || value == '1900/01/01 00:00:00') {
                  return res = '<span   onclick="CRUD.time(' + rows.KeyId + ",'')\">暂无</span>"
                } else {
                  return res = '<span   onclick="CRUD.time(' + rows.KeyId + ",'" + value + "')\">" + value + '</span>'
                }
              }

            },
            {
              field: 'RepairRemark',
              title: '养护意见',
              cellStyle: {
                css: {
                  color: 'red'
                }
              },
              align: 'center',
              sortable: true,
              formatter: function (value, rows, index) {
                if (value == null || value == 'null' || value == '') {
                  return res = '<span   onclick="CRUD.remark(' + rows.KeyId + ",'')\">暂无</span>"
                } else {
                  return res = '<span   onclick="CRUD.remark(' + rows.KeyId + ",'" + value + "')\">" + value + '</span>'
                }
              }
            },
            {
              field: 'Pic',
              title: '照片',
              cellStyle: {
                css: {
                  color: 'red'
                }
              },
              align: 'center',
              formatter: function (value, row, index) {
                if (value) {
                  return getImgContent(value, row, index)
                }
              }
            },

            {
              field: 'Status',
              title: '状态',

              align: 'center',
              sortable: true,
              formatter: function (value, row, index) {
                var res = ''
                switch (value) {
                  case '设施科未处理':
                    res = '<span)" style="color:red" >' + value + '</span>'
                    break
                  case '领导未审核':
                    res = '<span)" style="color:purple" >' + value + '</span>'
                    break
                  case '领导立案':
                    res = '<span)" style="color:blue" >' + value + '</span>'
                    break
                  case '领导不立案':
                    res = '<span)" style="color:#808080" >' + value + '</span>'
                    break
                  case '设施科未验收':
                    res = '<span)" style="color:blue" >' + value + '</span>'
                    break
                  case '养护合格':
                    res = '<span)" style="color:green" >' + value + '</span>'
                    break
                  case '养护不合格':
                    res = '<span)" style="color:#808080" >' + value + '</span>'
                    break
                  case '所长已处理':
                    res = '<span)" style="color:#808080" >' + value + '</span>'
                    break
                  case '初报未处理':
                    res = '<span)" style="color:#808080" >' + value + '</span>'
                    break
                  case '养护未反馈':
                    res = '<span)" style="color:#808080" >' + value + '</span>'
                    break
                  case '设施科生成养护单':
                    res = '<span)" style="color:#808080" >' + value + '</span>'
                    break
                  case '养护未验收':
                    res = '<span)" style="color:#808080" >' + value + '</span>'
                    break
                  case '环投生成养护单':
                    res = '<span)" style="color:#808080" >' + value + '</span>'
                    break
                  case '设施科标记大中修':
                    res = '<span)" style="color:#808080" >' + value + '</span>'
                    break
                  case '设施科返回所内处理':
                    res = '<span)" style="color:#808080" >' + value + '</span>'
                    break
                  case '设施科验收病害':
                    res = '<span)" style="color:#808080" >' + value + '</span>'
                    break
                }
                return res
              },
              sortable: true
            }, {
              field: 'AreaName',
              title: '区域',
              cellStyle: {
                css: {
                  color: 'red'
                }
              },
              align: 'center',
              visible: false
            },
            {
              field: 'KeyId',
              title: '有无历史病害',
              cellStyle: {
                css: {
                  color: 'red'
                }
              },
              align: 'center',
              formatter: function (value, row, index) {
                var res = ''
                $.ajax({
                  url: actionURL + '/api/harm/GetHistotyDefect/' + value,

                  async: false,

                  success: function (d) {
                    if (d != '[]') {
                      res = '有'
                    } else {
                      res = '无'
                    }
                  }

                })
                return res
              }
            }
          ],
          method: 'get',
          url: actionURL + '/api/harm/GetDiseasesByID/785',
          // toolbar: '#exampleTableEventsToolbar',//自定义工具栏
          striped: true, // 设置为 true 会有隔行变色效果
          search: false, // 是否启用搜索框
          showRefresh: false, // 是否显示刷新按钮
          pagination: true, // 是否启用分页控件
          pageNumber: 1,
          sortName: 'RecordTime',
          sortable: true,
          sortOrder: 'asc',
          // singleSelect: true,//单选
          pageSize: 10, // 如果设置了分页，页面数据条数
          pageList: [10, 20, 40], // 设置可供选择的页面数据条数
          sidePagination: 'server', // 设置为服务器端分页
          clickToSelect: true, // 设置true 将在点击行时，自动选择rediobox 和 checkbox
          singleSelect: true, // 单选checkbox
          onClickRow: function (row, tr, flied) {
            // ClearHtmlMarker();
            if (!row[0]) {
              IsChecked = true
              ClearHtmlMarker()
              layer.msg('开始标注')
              $('#PointX').val(row.X)
              $('#PointY').val(row.Y)
              $('#PointZ').val(row.Z)
              $('#ComponentCode').val(row.ComponentCode)
              $('#TargetXYZ').val(row.CameraXYZ)
              $('#KeyId').val(row.KeyId)
              if (row.ComponentCode != null && row.X != null) {
                var markerMgr = bimEngine.getMarkerManager()
                var id = new Date().getTime() + 1000
                var domId = 'marker' + id
                var html = '<div id="' + domId + '" style="position: absolute;">' +
                  '<img src="../sdk/bimviz/viz/data/images/markers/business.png" width="30" height="40">' +
                  '</div>'
                var point = new THREE.Vector3(row.X, row.Y, row.Z)
                var marker = new BIMVIZ.HtmlMarker(id, domId, domId, point, html, BIMVIZ.Align2D.BottomCenter, 0, 'htmlmarker', 'marker-text')
                markerMgr.addHtmlMarker(marker)

                bimEngine.acquireSpacePoint(function (data) {

                })
                var target = new THREE.Vector3(row.CameraXYZ.split(',')[0], row.CameraXYZ.split(',')[1], row.CameraXYZ.split(',')[2])
                var point1 = new THREE.Vector3(row.X, row.Y, row.Z)
                bimEngine.flyFromTo(target, point1)
              }
            } else {
              IsChecked = false
              $('#PointX').val('')
              $('#PointY').val('')
              $('#PointZ').val('')
              $('#ComponentCode').val('')
              $('#TargetXYZ').val('')
              $('#KeyId').val('')
            }
          }
        })
      },
      getSelectedRow: function () {
        return $('#TbHarmData').bootstrapTable('getSelections')
      },
      reload: function () {
        // 刷新列表数据
        // $('#table').bootstrapTable('refresh', { url: actionURL + '?new=' + Math.random() });
        $('#TbHarmData').bootstrapTable('refresh')
      }
    }
    grid.bind()

    var count = 1

    function getImgContent (value, row, index) {
      console.log(row)

      var htmlLi = ''
      var pics = value.split('@')
      pics[0] = pics[0].split('.jpg')[0]
      // var htmlAStart = "<a href='#' onclick='showPics(\'imgs_" + row.ROWID + "\');'><i style='width:50px;height:80px;background-repeat:no-repeat;background-size: cover;background-position: center; background-image:url(" + PicURL+ row.path + pics[0] + ".jpg);  display: block'   id='imgs_" + row.ROWID + "'><ul style='display: none;'>";
      var htmlAStart = '<a href="#" onclick="showPicLayer(\'' + PicURL + row.path + '\',\'' + value + ' \',\'' + row.ItemDescription + '/' + row.ItemName + '/' + row.RecordDescription + '\');"><i style="width:50px;height:80px;background-repeat:no-repeat;background-size: cover;background-position: center; background-image:url(' + PicURL + row.path + pics[0] + '.jpg);  display: block"   id="imgs_' + count + '"><ul style="display: none;">'
      count++
      var pics_new = value.split('@')
      $(pics_new).each(function (i) {
        pics_new[i] = pics_new[i].split('.jpg')[0]
        htmlLi += '<li><img data-original="' + PicURL + row.path + pics_new[i] + '.jpg" src="' + PicURL + row.path + pics_new[i] + '.jpg" alt="' + row.ItemDescription + '/' + row.ItemName + '/' + row.RecordDescription + '"></li>'
      })
      var htmlAEnd = '</ul></i></a>'
      return htmlAStart + htmlLi + htmlAEnd
    }

    function ClearHtmlMarker () {
      var markerMgr = bimEngine.getMarkerManager()
      // SaveArr = [];
      // var htmlmarkerList = markerMgr.getHtmlMarkerList();
      // if (htmlmarkerList.length > 0) {
      // for (var i = 0; i < htmlmarkerList.length; i++) {
      // markerMgr.removeHtmlMarker(htmlmarkerList[i].id);
      // bimEngine.requestOneUpdate();
      // }
      // }
      markerMgr.showAllHtmlMarker(false)
    }

    bimEngine.addListener(BIMVIZ.EVENT.OnPickElement, function (evt) {
      ClearHtmlMarker()
      if (IsChecked) {
        var componentID = evt.args.elementId
        var componentData = bimEngine.projectData.bimScene.ElementList
        var ComponentCode

        var markerMgr = bimEngine.getMarkerManager()
        var id = new Date().getTime() + 1000
        var domId = 'marker' + id
        var html = '<div id="' + domId + '" style="position: absolute;">' +
          '<img src="../sdk/bimviz/viz/data/images/markers/business.png" width="40" height="40">' +
          '</div>'
        var point = evt.args.point.sub(bimEngine.CenterPosition)
        var marker = new BIMVIZ.HtmlMarker(id, domId, domId, point, html, BIMVIZ.Align2D.BottomCenter, 0, 'htmlmarker', 'marker-text')
        markerMgr.addHtmlMarker(marker)

        bimEngine.acquireSpacePoint(function (data) {

        })
        for (var i = 0; i < componentData.length; i++) {
          if (componentID == componentData[i].Id) {
            $('#ComponentCode').val(componentData[i].Name.split(':')[1])
            break
          }
        }
        bimEngine.flyToElement(evt.args.elementId)
        $('#PointX').val(point.x)
        $('#PointY').val(point.y)
        $('#PointZ').val(point.z)
        var position = bimEngine.getCameraTarget()
        $('#CameraXYZ').val(position.x + ',' + position.y + ',' + position.z)
        bimEngine.requestOneUpdate()
      } else {
        bimEngine.requestOneUpdate()
      }
    })

    $('#btn_SavePoint').click(function () {
      if (IsChecked) {
        if ($('#KeyId').val() != '') {
          $.ajax({
            url: _DEFAULTPATH + '/bimviz/update/DailyDefectRecord',
            cache: true,
            type: 'Post',
            async: true,
            data: {
              X: $('#PointX').val(),
              Y: $('#PointY').val(),
              Z: $('#PointZ').val(),
              CameraXYZ: $('#CameraXYZ').val(),
              ComponentCode: $('#ComponentCode').val(),
              KeyId: $('#KeyId').val()
            },
            success: function (result) {
              if (result) {
                layer.alert('标记成功！')
                grid.reload()
              }
            },
            error: function (err) {
              layer.alert(err.responseText)
            }
          })
        }
      } else {
        layer.alert('请选择一行！')
      }
    })
  }
}
